package com.lxy.cloud.mqtt.client.service.impl;

import com.lxy.cloud.mqtt.client.model.dto.MqttGetDTO;
import com.lxy.cloud.mqtt.client.model.vo.BaseCommandVO;
import com.lxy.cloud.mqtt.client.service.IMqttSender;
import com.lxy.cloud.mqtt.client.service.SendMsgService;
import com.lxy.cloud.mqtt.client.util.JsonUtil;
import com.lxy.cloud.mqtt.client.util.ValidatorUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Objects;
import java.util.UUID;

/**
 * @Author: lxy
 * @Date: 2020/9/7 16:55
 * @Desc: 发送Mqtt消息
 */
@Service
public class SendMsgServiceImpl implements SendMsgService {

    @Autowired
    private IMqttSender mqttSender;

    @Override
    public void sendMsg(BaseCommandVO mqttMsg) {
        //检验参数合法性
        ValidatorUtils.validateEntity(mqttMsg);
        MqttGetDTO resp = new MqttGetDTO();
        resp.setMethod(mqttMsg.getMethod());
        Object data = mqttMsg.getData();
        if (Objects.nonNull(data)) {
            resp.setData(data);
        }
        resp.setVersion("1.0.0");
        resp.setRequestId(UUID.randomUUID().toString().replaceAll("-", ""));
        resp.setTimestamp(System.currentTimeMillis());
        mqttSender.sendToMqtt(mqttMsg.getTopic(), JsonUtil.create().objectToJson(resp));
    }
}
